package com.romotc.qqrobot.bean;

import java.util.List;

import org.codehaus.jackson.map.DeserializerFactory.Config;

import com.romotc.qqrobot.config.QQUrlWatcherConfigService;
import com.romotc.qqrobot.config.bean.QQUrlWatcherConfig;

public class QQDataService {

	private static QQData instance = new QQData();

	
	/**
	 * 根据reqUrl取得最新的模板
	 * @param reqUrl
	 * @return
	 */
	public static QQData qryLatestQQDataTemplet(String reqUrl) {
		int idx = reqUrl.indexOf("?");
		if(idx != -1) {
			reqUrl = reqUrl.substring(0, idx);
		}
		
		QQUrlWatcherConfig urlConfig = QQUrlWatcherConfigService.getConfigByUrl(reqUrl, null);
		if(!"*".equals(urlConfig.getUrl()) && urlConfig != null) {
			long urlId = urlConfig.getId();
			return qryLatestQQDataTemplet(urlId);
		}
		
		return null;
	}

	/**
	 * 根据reqUrl取得最新的模板
	 * @param reqUrl
	 * @return
	 */
	public static QQData qryLatestQQDataTemplet(long urlId) {
		List<QQData> templets = (List<QQData>)instance.Filter("urlId = " + urlId + " and templetVersion > " + 0, 1, 1);
		if(templets != null && !templets.isEmpty()) {
			QQData retQData = instance;
			for(QQData qData : templets) {
				if(qData.getTempletVersion() > retQData.getTempletVersion())
					retQData = qData;
			}
			return retQData;
		}
		return null;
	}

	/**
	 * 取响应模板
	 * @param url
	 * @param isGetNew 如果没有配置模板是否获取最新一次请求的数据
	 * @return
	 */
	public static QQData qryLatestQQDataTemplet(String url, boolean isGetNew) {
		QQData temple = qryLatestQQDataTemplet(url);
		
		if(temple == null && isGetNew) {
			temple = qryLatestQQData(url);
			return temple;
		}else {
			return temple;
		}
	}

	/**
	 * 获取url最新一次的请求数据
	 * @param url
	 * @return
	 */
	public static QQData qryLatestQQData(String reqUrl) {
		int idx = reqUrl.indexOf("?");
		if(idx != -1) {
			reqUrl = reqUrl.substring(0, idx);
		}
		
		QQUrlWatcherConfig urlConfig = QQUrlWatcherConfigService.getConfigByUrl(reqUrl, null);
		if(!"*".equals(urlConfig.getUrl()) && urlConfig != null) {
			long urlId = urlConfig.getId();
			return qryLatestQQData(urlId);
		}
		
		return null;
	}

	/**
	 *
	 * 获取url最新一次的请求数据
	 *
	 * @param urlId
	 * @return
	 */
	private static QQData qryLatestQQData(long urlId) {
		//默认就是按照id排序
		List<QQData> qqDatas = (List<QQData>)instance.Filter("urlId = " + urlId, 1, 1);
		if(qqDatas != null && !qqDatas.isEmpty()) {
			QQData retQData = qqDatas.get(0);
			return retQData;
		}
		return null;
	}
}
